<!--危险物质列表-->
<template>
  <section class="content" id="mhmContent">
    <!-- 表格区 -->
    <div class="table">
      <lq-table ref="mhmTableRef"
                :columns="columns"
                :records="mhmTableData.records"
                @on-selections="handleSelections"
                size="default"
                :border="true"
                :stripe="true"
      >
        <template #isToxic="scope">
          <div>{{scope.row.isToxic ?'是':'否'}}</div>
        </template>
        <template #operate="scope">
          <el-button @click="handleEdit(scope.row)" type="primary">编辑</el-button>
          <el-button @click="() => {
                      isDeleteBatch = false;
                      delId = [scope.row.id];
                      lqtableCommon.handleRemove([scope.row.id], handleRemove);
                   }"
                     type="danger">删除</el-button>
        </template>
      </lq-table>
    </div>
    <el-row>
      <el-col :span="24" align="left" style="margin-top:5px;font-size: 40px" v-if="optCase.id != '' && optCase.hazardCode != ''">
          <el-icon @click="()=>{
            materialOptCase.operaCase='add';
            materialDialog.visible = true;
          }">
            <CirclePlusFilled color="rgb(64,133,233)" style="cursor: pointer;"/>
          </el-icon>
      </el-col>
    </el-row>
    <!-- 新增模态框 -->
    <el-dialog v-model="materialDialog.visible"
               destroy-on-close
               v-bind="{...materialDialog.innerAttrs}"
               v-on="materialDialog.events"
               :before-close="closeMaterialDialog">
      <el-row>
        <el-col :span="24">
          <major-hazard-material-form
              ref="hazardMaterialFormRef"
              @flush="flush"
          >
          </major-hazard-material-form>
        </el-col>
      </el-row>
    </el-dialog>
  </section>
</template>

<script setup lang="ts">
import {defineEmits} from "vue/dist/vue";

/**
 * 全局方法引入
 */
const global = getCurrentInstance().appContext.config.globalProperties;

import {
  ref,
  reactive,
  onMounted,
  toValue,
  getCurrentInstance,
  inject,
  defineExpose,
  provide,
} from "vue";
import {FormInstance, FormRules} from "element-plus";

import {ElMessage, ElMessageBox} from "element-plus";
import lqtableCommon from '../../components/lqtableCommon.js';
import {editKey, editMaterialKey} from '../../components/keys.js';
import LqTable from '@/pages/components/LqTable.vue'
import MajorHazardMaterialForm from '@/pages/ent/majorHazard/MajorHazardMaterialForm.vue'


//========== provide and inject ==========
//是否显示新增、编辑按钮栏, 查看不显示
const materialOptCase = ref({
  operaCase: 'view',
  id: '',
  hazardInfoId: '',
  hazardCode: '',
  closeDialog: ()=>{
    materialDialog.value.visible = false;
  }
});
provide(editMaterialKey, materialOptCase);


const optCase = inject(editKey);

//================ table =============
const columns = [
  {label: '', type: "selection", width: 40},
  {label: '序号', type: "index", width: 50},
  {label: '危险物质名称', prop: 'name', type: 'link', minWidth: 200, event: {
    click: (row) => {
      materialOptCase.value.operaCase = 'view';
      materialOptCase.value.id = row.id;
      materialOptCase.value.hazardInfoId = row.hazardInfoId;
      materialOptCase.value.hazardCode = row.hazardCode;
      materialDialog.value.innerAttrs.title = '查看危险物质';
      materialDialog.value.visible = true;
    }
   }},
  {label: "是否剧毒", prop: 'isToxic', slotName: 'isToxic', slotted: true, minWidth: 80},
  {label: '校正系数', prop: 'betaValue', minWidth: 120},
  {label: "在线存在量（吨）", prop: 'onlineStore', minWidth: 250},
  {label: "临界值（吨）", prop: 'critValue', minWidth: 100},
  {label: '操作', prop: 'id', slotName: 'operate', slotted: true, align: 'center', fixed: 'right', minWidth: 150},
];

const mhmTableRef = ref();

const mhmTableData = ref({
  records: [],
  // pageSize: 10,
  tableSize: 'default',
  border: true,
});

//================ dialog ============
const hazardMaterialFormRef = ref()

const materialDialog = ref({
  visible: false,
  innerAttrs: {
    id: 'materialFormDialog',
    class: 'majorHazardMaterialFormDialog',
    title: '新增危险物质',
    width: "80%",
    top: '1vh'
  },
  events: {
    open: () => {
      console.log('dialog open.....');
    },
    close: () => {
      console.log('dialog close.....');
      // hazardMaterialFormRef.value?.handleReset();

    },
  }
})
//
const closeMaterialDialog = (done: () => void) => {
  hazardMaterialFormRef.value.handleReset();
  done();
}

//查看或编辑
const viewOrEditHazardMaterial = (row) => {
  // console.log(row.id, row.name, row.isToxic);
}

//================= load ===============
const loadData = () => {
  mhmTableRef.value?.startLoading();
  global.$api.getMajorHazardMaterialList({
    hazardInfoId: optCase.value.hazardInfoId,
    hazardCode: optCase.value.hazardCode
  }).then( ({data}) => {
    if (data.status === 'OK') {
      mhmTableRef.value?.stopLoading();
      mhmTableData.value.records = data.data;
    }
  });
}

const flush = () => {
  materialDialog.value.visible = false;
  loadData();
}

onMounted(() => {
  if (optCase.value.id !== '' && optCase.value.hazardInfoId !== '') {
    loadData();
  }
})
//==================== edit =================
const handleEdit = (row) => {
  materialOptCase.value.operaCase = 'edit';
  materialOptCase.value.id = row.id;
  materialOptCase.value.hazardInfoId = row.hazardInfoId;
  materialOptCase.value.hazardCode = row.hazardCode;
  materialDialog.value.visible = true;
}

//==================== delete ===============
// 删除功能
const isDeleteBatch = ref(false);
const delId = ref([]);
//选择的记录集
const selections = ref([]);
//是否显示指删除按钮
const emit = defineEmits<{
  (e: 'showDelBatchBtn', value: Boolean): void
}>()

//删除一行
const handleRemove = () => {
  global.$api.deleteMaterialByIds({
      ids: (isDeleteBatch.value ? selections.value : delId.value),
  }).then( ({data}) => {
      ElMessage({type: "success", message: "您已经成功删除所选记录！"});
      loadData();
  }).catch((err) => {
      ElMessage({type: "error", message: "服务器端错误删除记录失败！"});
  });
};
//批量删除
const deleteBatch = () => {
  lqtableCommon.handleRemove(toValue(selections), handleRemove)
}

//============================ Copy =================================
const handleSelections = (items) => {
  //指删除
  isDeleteBatch.value = true;
  selections.value = items.value.map((item) => item.id);
  const flag = (selections.value.length !== 0 ? true : false);
  emit('showDelBatchBtn', flag);
}

defineExpose({
  deleteBatch
})
</script>

<style scoped>

</style>
